package com.beemans.corekit.ui.activity;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.util.Consumer;
import androidx.viewbinding.ViewBinding;

import com.beemans.corekit.integration.toolkit.ActivityUtils;
import com.beemans.corekit.utils.IntentUtils;
import com.beemans.corekit.utils.PermissionUtils;

@RequiresApi(api = Build.VERSION_CODES.R)
public class AllFileAccessPermissionActivity extends BaseActivity<ViewBinding> {
    private final Handler handler = new Handler(Looper.getMainLooper());

    @Nullable
    private Runnable permissionCheckRunnable = null;
    private boolean isFinished = false;

    @Nullable
    private static Consumer<Boolean> permissionCallback = null;

    @Nullable
    @Override
    protected ViewBinding getViewBinding() {
        return null;
    }

    @Override
    protected void initViews() {
    }

    @Override
    public void initEvents() {
        // 启动系统设置页面申请所有文件访问权限
        registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 从设置页面返回后检查权限状态
                    finishWithResult(PermissionUtils.hasAllFileAccessPermission());
                }
        ).launch(IntentUtils.getAllFileAccessIntent(this));

        // 开始轮询检查权限状态
        startPermissionStatusCheck();
    }

    /**
     * 开始检测所有文件访问权限状态
     * 使用轮询方式检测，因为用户可能在设置页面授予权限后不立即返回
     */
    private void startPermissionStatusCheck() {
        stopPermissionStatusCheck();

        permissionCheckRunnable = () -> {
            if (PermissionUtils.hasAllFileAccessPermission()) {
                // 权限已授予，重新启动该Activity以确保系统设置页面正确关闭
                ActivityUtils.startActivity(AllFileAccessPermissionActivity.class);
                finishWithResult(true);
            } else {
                // 权限未授予，继续检查
                if (permissionCheckRunnable != null) {
                    handler.postDelayed(permissionCheckRunnable, 100);
                }
            }
        };

        // 延迟300ms开始检查，给系统设置页面启动时间
        handler.postDelayed(permissionCheckRunnable, 300);
    }

    /**
     * 停止权限状态检测
     */
    private void stopPermissionStatusCheck() {
        if (permissionCheckRunnable != null) {
            handler.removeCallbacks(permissionCheckRunnable);
            permissionCheckRunnable = null;
        }
    }

    /**
     * 完成权限申请并返回结果
     *
     * @param hasPermission 是否已获得所有文件访问权限
     */
    private void finishWithResult(boolean hasPermission) {
        if (isFinished) return;
        isFinished = true;

        stopPermissionStatusCheck();
        ActivityUtils.finishActivity(this, false);

        if (permissionCallback != null) {
            permissionCallback.accept(hasPermission);
            permissionCallback = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPermissionStatusCheck();
        permissionCallback = null;
    }

    /**
     * 启动所有文件访问权限申请Activity
     *
     * @param callback 权限申请结果回调
     */
    public static void start(@NonNull Consumer<Boolean> callback) {
        AllFileAccessPermissionActivity.permissionCallback = callback;
        ActivityUtils.startActivity(AllFileAccessPermissionActivity.class);
    }
}